package net.jjjshop.common.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.jjjshop.common.entity.lbt.TeamBean;
import net.jjjshop.common.entity.order.OrderAddress;
import net.jjjshop.common.entity.user.User;
import net.jjjshop.common.entity.user.UserGrade;
import net.jjjshop.common.mapper.user.UserMapper;
import net.jjjshop.common.service.user.UserGradeService;
import net.jjjshop.common.service.user.UserService;
import net.jjjshop.common.util.BigDecimalUtil;
import net.jjjshop.framework.common.service.impl.BaseServiceImpl;
import net.jjjshop.framework.util.LoginUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户记录表 服务实现类
 *
 * @author jjjshop
 * @since 2022-07-01
 */
@Slf4j
@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userDao;
    @Autowired
    private UserGradeService userGradeService;

    @Override
    public TeamBean queryTeam(Integer uid, BigDecimal payMonet) {
        return getNewTeam(uid,payMonet);
    }


    /**
     * 新模式团队统计
     * @param
     * @return
     */
    private TeamBean getNewTeam(Integer uid,BigDecimal payMonet){
        // int all = 0;
        User byId = getById(uid);
        byId.setAllAv(BigDecimalUtil.addDouble(byId.getAllAv(),payMonet));
//        userDao.updateById(byId);
        TeamBean teamBean   = new TeamBean();
        teamBean.setNum(0);
        teamBean.setPrice(byId.getPayMoney());
        System.out.println("byId.getFirstPay()="+byId.getPayMoney());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("referee_id", uid);
        List<User> list = this.list(queryWrapper);
        if (null != list && !list.isEmpty()){
            teamBean.setNum(list.size());
            for (User user : list){

                if (user.getGradeId() == 1){
                    teamBean.setMdNum(1+teamBean.getMdNum());
                }
                if (user.getGradeId() == 2){
                    teamBean.setDlNum(1+teamBean.getDlNum());
                }
                if (user.getGradeId() == 3){
                    teamBean.setHhNum(1+teamBean.getHhNum());
                }
                if (user.getGradeId() == 4){
                    teamBean.setDsNum(1+teamBean.getDsNum());
                }
            }
        }
//
        if (byId.getAllAv().doubleValue() > 50000){
            if (byId.getAllAv().doubleValue() > 3200000 && teamBean.getHhNum() >= 2){
//                teamBean.setDsNum(teamBean.getDsNum()+1);
                if (byId.getLevel() <4){
                    byId.setLevel(4);
                }

            }else
            if (byId.getAllAv().doubleValue() > 800000 && teamBean.getDlNum() >= 2){
//                teamBean.setHhNum(teamBean.getHhNum()+1);
                if (byId.getLevel() <3){
                    byId.setLevel(3);
                }
            }else
            if (byId.getAllAv().doubleValue() > 200000 && teamBean.getMdNum() >= 2){
//                teamBean.setDlNum(teamBean.getDlNum()+1);
                if (byId.getLevel() <2){
                    byId.setLevel(2);
                }
            }else
            if (byId.getAllAv().doubleValue() < 200000 || teamBean.getMdNum() < 2){
//                teamBean.setMdNum(teamBean.getMdNum()+1);
                if (byId.getLevel() <1){
                    byId.setLevel(1);
                }
            }

        }
        if (byId.getAllAv().doubleValue() > 10000000 && teamBean.getDsNum() >= 2){
            byId.setLevel(5);
            //这个8的是分红用户
        }
       LambdaQueryWrapper<UserGrade> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserGrade::getWeight,byId.getLevel());
        UserGrade one = userGradeService.getOne(wrapper);
        if (null != one){
            byId.setGradeId(one.getGradeId());
        }
        this.updateById(byId);

        return teamBean;
    }


    @Override
    public Integer selectInviteCodeNum(Integer pid) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("referee_id", pid);
        queryWrapper.ge("order_num",1);//有效订单
        return this.count(queryWrapper);
    }

    @Override
    public Integer getUserId() {
        return LoginUtil.getUserId();
    }
    //查询上级用户
    public Boolean getParentUser(Integer uid,BigDecimal payPrice){
        User users = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserId, uid));
        if (users != null){
            Integer spid = users.getRefereeId();
            while (true){
                if (spid == 0){
                    this.getParentMember(uid);
                    break;
                }
                User parentUser = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserId, spid));
                if (parentUser == null){
                    break;
                }
                spid = parentUser.getRefereeId();
                if (parentUser != null){
                    //增加团队业绩
                    System.out.println("增加团队业绩增加团队业绩增加团队业绩");
                    User userEntity = new User();
                    userEntity.setAllAv(BigDecimalUtil.addDouble(parentUser.getAllAv(),payPrice));
                    userEntity.setUserId(parentUser.getUserId());
                    this.updateById(userEntity);
                }
            }
        }
        return true;
    }

    //查询上级用户计算等级
    public Boolean getParentMember(Integer uid){
        User users = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserId, uid));
        User userEntity = null;
        if (users != null){
            Integer spid = users.getPid();
            while (true){
                if (spid == 0){
                    break;
                }
                User parentUser = this.getOne(new LambdaQueryWrapper<User>().eq(User::getUserId, spid));
                if (parentUser == null){
                    break;
                }
                spid = parentUser.getRefereeId();
                if (parentUser != null){
                    //当您业绩达到5万元，就成为门店
                    if (parentUser.getAllAv().compareTo(new BigDecimal(50000)) > 0) {
                        userEntity = new User();
                        userEntity.setLevel(1);
                        userEntity.setUserId(parentUser.getUserId());
                        this.updateById(userEntity);
                    }
                    //当您直推二个门店+20万总业绩时,您就成为公司代理
                    if (parentUser.getAllAv().compareTo(new BigDecimal(200000)) > 0) {
                        Integer levelCount = userDao.getUserLevelCount(parentUser.getUserId(), 1);
                        if (levelCount == 2) {
                            userEntity = new User();
                            userEntity.setLevel(2);
                            userEntity.setUserId(parentUser.getUserId());
                            this.updateById(userEntity);
                        }
                    }
                    //当您团队有二个代理+80万总业绩时，您就成为公司合伙人
                    if (parentUser.getAllAv().compareTo(new BigDecimal(800000)) > 0) {
                        Integer levelCount = userDao.getUserLevelCount(parentUser.getUserId(), 2);
                        if (levelCount == 2) {
                            userEntity = new User();
                            userEntity.setLevel(3);
                            userEntity.setUserId(parentUser.getUserId());
                            this.updateById(userEntity);
                        }
                    }
                    //当您团队有二个合伙人+320万总业绩时，您就成为公司董事成员
                    if (parentUser.getAllAv().compareTo(new BigDecimal(320000)) > 0) {
                        Integer levelCount = userDao.getUserLevelCount(parentUser.getUserId(), 2);
                        if (levelCount == 2) {
                            userEntity = new User();
                            userEntity.setLevel(4);
                            userEntity.setUserId(parentUser.getUserId());
                            this.updateById(userEntity);
                        }
                    }
                }
            }
        }
        return true;
    }

    public Boolean handleTeamPerformance(Integer uid,BigDecimal payPrice){

        return true;
    }

    @Override
    public User getByAccount(String account) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getMobile, account);
        return userDao.selectOne(lqw);
    }

    @Override
    public String setUserRegin(Integer uid, Integer reginId) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getRegionAgent,reginId+"");
        List<User> list = list(wrapper);
        if (null != list && !list.isEmpty()){
            return "已经有存在区域";
        }
        User byId = getById(uid);
        if (null != byId){
            if (StringUtils.isNotEmpty(byId.getRegionAgent())){
                byId.setRegionAgent(byId.getRegionAgent()+","+reginId);
            }else{
                byId.setRegionAgent(reginId+"");
            }
            updateById(byId);
            return "200";
        }

        return "设置异常";
    }

    @Override
    public BigDecimal getAline(Integer uid) {
        User byId = getById(uid);
        Set<Integer> uid1 = getUid(byId);
        uid1.add(uid);
        if (null == uid1 || uid1.isEmpty()){
            return  new BigDecimal(0);
        }
        return userDao.getLineMoney(new ArrayList<>(uid1));
    }

    @Override
    public Integer getGjdlNum(Integer uid) {
        User byId = getById(uid);
        Set<Integer> uid1 = getUid(byId);
        uid1.add(uid);
        if (null == uid1 || uid1.isEmpty()){
            return  0;
        }
        return  userDao.level33(new ArrayList<>(uid1));
    }

    @Override
    public Integer getAllDlNum(Integer uid) {
        User byId = getById(uid);
        Set<Integer> uid1 = getUid(byId);
        uid1.add(uid);
        if (null == uid1 || uid1.isEmpty()){
            return  0;
        }
        return  userDao.level44(new ArrayList<>(uid1));
    }


    private Set<Integer> getUid(User byId){
        Set<Integer> uidList = new HashSet<>();
        if (null!=byId&& null != byId.getAline()){
            uidList.add(byId.getAline());
            uidList.addAll(getUid(byId.getAline()));
        }
        if (null!=byId&& null != byId.getBline()){
            uidList.add(byId.getBline());
            uidList.addAll(getUid(byId.getBline()));
        }
        if (null!=byId&& null != byId.getCline()){
            uidList.add(byId.getCline());
            uidList.addAll(getUid(byId.getCline()));
        }
        return uidList;
    }

    private List<Integer> getUid(Integer uid){
        User byId = getById(uid);
        if (null == byId){
            return new ArrayList<>();
        }
        List<Integer> uidList = new ArrayList<>();
        if (null != byId.getAline()){
            uidList.add(byId.getAline());
            uidList.addAll(getUid(byId.getAline()));
        }
        if (null != byId.getBline()){
            uidList.add(byId.getBline());
            uidList.addAll(getUid(byId.getBline()));
        }
        if (null != byId.getCline()){
            uidList.add(byId.getCline());
            uidList.addAll(getUid(byId.getCline()));
        }

        return uidList;

    }


    @Override
    public BigDecimal getYjMoney(Integer uid) {
        List<User> tjUid = getTjUid(uid);
        List<Integer> uidList = new ArrayList<>();
        for (User user : tjUid){
            uidList.add(user.getUserId());
        }
        if (!uidList.isEmpty()){
            BigDecimal lineMoney = userDao.getLineMoney(uidList);
            return  lineMoney;
        }
        return new BigDecimal(0);
    }

    private List<User> getTjUid(Integer uid){
        List<User> list = new ArrayList<>();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(User::getUserId,User::getRefereeId);
        wrapper.eq(User::getRefereeId,uid);
        List<User> users = userDao.selectList(wrapper);
        if (null != users && !users.isEmpty()){
            list.addAll(users);
            for (User user : users){
                List<User> tjUid = getTjUid(user.getUserId());
                list.addAll(tjUid);
            }
        }

        return list;

    }

}
